package com.blog.controller.background;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.blog.entity.Link;
import com.blog.listener.event.InitComponentEvent;
import com.blog.service.background.ILinkService;

@Controller
@RequestMapping("/link")
public class LinkController {
	@Autowired
	ILinkService linkService;
	
	@Autowired
	private ApplicationEventPublisher publisher;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/getAllLink")
	@ResponseBody
	public String getAllLink(Integer page,Integer rows) {
		HashMap<String,Object> map = linkService.getAllLink(page,rows);
		List<Link> linkList = (List<Link>) map.get("linkList");
		JSONObject js = new JSONObject();
		js.put("total", map.get("total"));
		js.put("rows", linkList);
		return js.toString();
	}
	
	@RequestMapping("/getLinkById")
	@ResponseBody
	public String getLinkById(int id) {
		Link link = linkService.getLinkById(id);
		JSONObject js = new JSONObject();
		js.put("link", link);
		return js.toString();
	}
	
	@RequestMapping("/removeLinkByIds")
	@ResponseBody
	public String removeLinkByIds(int[] arrId,HttpServletRequest request) {
		int i = linkService.removeLinkByIds(arrId);
		if(i>0) {
			this.commonRefreshSystemCache(request);
			return "success";
		}
		return "false";
	}	
	
	@RequestMapping("/updateLinkById")
	@ResponseBody
	public String updateLinkById(Link link,HttpServletRequest request) {
		int i = linkService.updateByPrimaryKeySelective(link);
		if(i>0) {
			this.commonRefreshSystemCache(request);
			return "success";
		}
		return "false";
	}
	
	@RequestMapping("/addNewLink")
	@ResponseBody
	public String addNewLink(Link link,HttpServletRequest request) {
		int i = linkService.addNewLink(link);
		if(i>0) {
			this.commonRefreshSystemCache(request);
			return "success";
		}
		return "false";
	}
	
	/**
	 * 异步刷新友情链接相关信息
	 * @param request
	 */
	private void commonRefreshSystemCache(HttpServletRequest request){
		try {
			InitComponentEvent event=new InitComponentEvent(this, 0,request);
			publisher.publishEvent(event);
		} catch (Exception e) {}
	}
	
}
